package com.sike.service;

import com.sike.entity.User;
import com.sike.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

/**
 * @author vito
 * @version 1.0
 */
@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;

    @Transactional
    public void updateBalance(Integer userId, BigDecimal balance) {
        User user = userMapper.findById(userId);
        BigDecimal newBalance = user.getBalance().add(balance);
        if (newBalance.compareTo(BigDecimal.ZERO) < 0) {
            throw new RuntimeException("余额不足");
        }
        user.setBalance(newBalance);
        userMapper.updateUser(user);
    }

    public BigDecimal getBalance(Integer userId) {
        User user = userMapper.findById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        return user.getBalance();
    }
}
